package com.budong.component;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;

import static com.budong.common.GifConstant.UPLOAD_QINIU_ERROR;

/**
 * Created by jianweilin on 2016/12/25.
 */
@Component
public class QiNiuComponent {

    @Value("${qiniu.access.key}")
    private String ACCESS_KEY;

    @Value("${qiniu.secret.key}")
    private String SECRET_KEY;

    @Value("${qiniu.bucketname}")
    private String bucketname;

    public  String uploadFile(String filePath){
        System.out.println("七牛云开始上传");
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

        Zone z = Zone.autoZone();
        Configuration c = new Configuration(z);

        //创建上传对象
        UploadManager uploadManager = new UploadManager(c);

        long start = System.currentTimeMillis();
        try {
            //调用put方法上传
            String key = UUID.randomUUID()+".gif";
            Response res = uploadManager.put(filePath, key, auth.uploadToken(bucketname));
            //打印返回的信息
            String uploadName = JSON.parseObject(res.bodyString()).get("key").toString();

            System.out.println("七牛云上传SPEND => " + ((System.currentTimeMillis() - start) / (double)1000) + " 秒");

            // return new StringBuilder("http://oiqclsogb.bkt.clouddn.com/").append(uploadName).toString();
            return new StringBuilder("http://img.soogif.com/").append(uploadName).toString();

        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        return UPLOAD_QINIU_ERROR;
    }
}
